package com.mytrans.client;

import com.mytrans.beans.ReturnObject;
import com.mytrans.util.JsonType;
import com.mytrans.util.ServletUtil;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Map;

public class RibbonClient {

    @Autowired
    private Client client;

    private String serverAplicationName = "mytrans-server";

    public <T> T execute(String url, RequestMethod method, Map<String, Collection<String>> header,
                                Object body, JsonType<T> resultType) throws IOException {
        url = "http://" + serverAplicationName + url;
        Request request = Request.create(method.name(), url, header, ServletUtil.obj2Body(body),
                StandardCharsets.UTF_8);
        Request.Options options = new Request.Options();
        Response response = client.execute(request, options);
        return ServletUtil.decode(response, resultType.getType());
    }
}
